﻿using System.Collections.Generic;
using System.Linq;

namespace Web.Infrastructure.Extensions
{
    public static class DictionaryExtensions
    {
        /// <summary>
        /// Returns a new dictionary sorted by value
        /// </summary>
        /// <typeparam name="TU"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static IDictionary<TU, T> SortByKeyValue<TU, T>(this IDictionary<TU, T> dict)
        {
            return dict.OrderBy(kvp => kvp.Value).Select(d => d).ToDictionary(pair => pair.Key, pair => pair.Value);
        }

        /// <summary>
        /// Returns a new dictionary sorted by value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static IDictionary<T, T> SortByValue<T>(this IDictionary<T, T> dict)
        {
            return dict.OrderBy(kvp => kvp.Value).Select(d => d).ToDictionary(pair => pair.Key, pair => pair.Value);
        }

        /// <summary>
        /// Returns a new dictionary sorted by value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static IDictionary<T, T> SortByValueDescending<T>(this IDictionary<T, T> dict)
        {
            return dict.OrderByDescending(kvp => kvp.Value).Select(d => d).ToDictionary(pair => pair.Key, pair => pair.Value);
        }
    }
}